var app = getApp();
import {
  api,
  util,
  dialog,
  storage
} from '../../../js/util'
import {
  pagesInfo,
  router
} from '../../../js/router'
import {
  profile,qywx,finance
} from "../../../js/modules/store.js"
import {
  info
} from "../../../js/modules/info.js"
import authorize from '../../../js/modules/authorize.js'
import {
  cart
} from '../../../js/modules/order.js'
import {
  credit
} from '../../../js/modules/credit.js'
import {
  config,
  domain
} from "../../../js/modules/gloab";
import {
  wholesaleSettings
} from "../../../js/modules/gloab";
import BasePage from '../../../js/common/base-page';
import { hideTabbar } from '../../../js/compatible';
import { alert } from '../../../js/newUtil';
BasePage({
  pageKey:"center",
  validateLogin: app.dns.fkId != app.dns.proprietorId,
  /**
   * 页面的初始数据
   */
  data: {
    isLogin:false,
    detail_show: '',
    imgDomain: api.imgDomain,
    enableOss:api.enableOss,
    storeInfo: {},
    hasNew: false, //是否有新消息  
    isBack: false,
    checkinIntegralEnable: false,
    wlzUrl:"",
    showlink:false,   //是否显示qywx联系人按钮
    orderlist:[
      { link: "/" + pagesInfo.orderList.url +"?tabWord=待支付", icon: 'icon-daifukuan', name: '待支付', dot: 0, key:'dfk', show: true },
      { link: "/" + pagesInfo.orderList.url + "?tabWord=待发货", icon: 'icon-daifahuo', name: '待发货', dot: 0, key:'dfh', show: true },
      { link: "/" + pagesInfo.orderList.url + "?tabWord=待收货", icon: 'icon-daishouhuo', name: '待收货', dot: 0, key:'dsh', show: true },
      { link: "/" + pagesInfo.orderList.url + "?tabWord=待评论", icon: 'icon-daipingjia', name: '待评价', dot: 0, key:'dpj', show: true },
      { link: "/" + pagesInfo.orderList.url + "?tabWord=已完成", icon: 'icon-yiwancheng', name: '已完成', dot: 0, key:'ywc', show: false },
      { link: "/" + pagesInfo.retreatList.url, icon:'icon-tuihuan', name: '退换货', dot: 0, key: 'thh', show: true},
    ],
    menulist:[
      { link: "/" + pagesInfo.integral.url, icon: 'icon-grade', name: '我的积分', key: 'grade', show: true },
      { link: "/" + pagesInfo.myCouponList.url, icon: 'icon-coupon', name: '我的优惠券', key: 'coupon', show: true },
      { link: "/" + pagesInfo.recharge.url, icon: 'icon-money', name: '我的预存款', key: 'money', show: true },
      { link: "/" + pagesInfo.billList.url, icon: 'icon-credit', name: '我的授信', key: 'credit', show: true },
      { link: "/" + pagesInfo.myGroupList.url + '?flag=1', icon: 'icon-group', name: '我的拼团', key: 'group', show: true },
      { link: "/" + pagesInfo.myGroupList.url + '?flag=2', icon: 'icon-presale', name: '我的预售', key: 'presale', show: true },
      { link: "/" + pagesInfo.arrears.url, icon: 'icon-arrears', name: '欠款订单', key: 'arrears', show: true },
      { link: "/" + pagesInfo.promotionlist.url, icon: 'icon-promotion', name: '促销活动', key: 'promotion', show: true },
      { link: "/" + pagesInfo.scantGoods.url, icon: 'icon-shortage', name: '缺货登记', key: 'shortage', show: true },
      { link: "/" + pagesInfo.commentList.url, icon: 'icon-comment', name: '我的评价', key: 'comment', show: true },
      { link: "/" + pagesInfo.distributionMain.url, icon: 'icon-fenxiao', name: '分销', key: 'distribution', show: false },
      { link: "/" + pagesInfo.dealing.url, icon: 'icon-dealing', name: '往来对账', key: 'dealing', show: true },
      { link: "/" + pagesInfo.userAccount.url, icon: 'icon-wode11', name: '我的账户', key: 'account', show: true }
    ],
    servicelist:[
      { link:"/"+ pagesInfo.receivedCouponList.url, img: 'market_coupon', name: '领券', key: 'market_coupon', show: true },
      { link:"/"+ pagesInfo.panicBuyList.url, img: 'market_sale', name: '特价', key: 'market_sale', show: true },
      { link:"/"+ pagesInfo.groupList.url+'?flag=2', img: 'market_presale', name: '预售', key: 'market_presale', show: true },
      { link:"/"+ pagesInfo.groupList.url +'?flag=1', img: 'market_group', name: '拼团', key: 'market_group', show: true }
    ],
    headerBg:"",
    loopCount:0,
    visitTimer:null,
    isIphoneX:app.globalData.isIphoneX,//苹果底部白线
    Initiator:0,
    IsStoreManagerAccount:-1,//判断子账号
    tabindex:-1,
    userFace:'',
    salesman:false,
    checkInInfo:{},
    showShadow: false,
    version:'',//版本 一代还是二代
    DisableSubaccount:false,
    ProprietorVersion:0,
    EnableSubaccount: 0, // 是否主体可使用主账户
    AllowModifyHeadIcon: false, // 是否允许自主修改客户门头照/头像
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();//隐藏分享
    this.giftPacks = this.selectComponent("#giftPacks");
    app.initTabBar();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  getCheckInInfo() {
    var that = this;
    finance.getCheckInInfo(function (res) {
      // console.log(res,'=========res');
      if (res.Success) {
        var content = res.Content;
        that.setData({
          checkInInfo: content
        });
      }
      else {
        that.setData({
          showShadow: false
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //隐藏原生底部导航
    hideTabbar()
    var tabindex = app.getTabBarindex();
    this.setData({
      tabindex:tabindex
    })
    this.isCanVisit(()=>{
      this.setData({
        isLogin: authorize.isLogin("store"),
        headerBg: api.titleColor||"#e56b14"
      })
      var storeInfo = authorize.getEntity();
      // console.log(storeInfo,'===storeInfo==1');
      if (storeInfo != undefined && storeInfo.role != undefined) {
        // storeInfo.role.Logo = this.data.imgDomain + storeInfo.role.Logo;
        this.setData({
          storeInfo: storeInfo,
          Initiator:storeInfo ? storeInfo.manager.Initiator:0,
          DisableSubaccount:storeInfo ?storeInfo.role.DisableSubaccount == '1':false
        });
      }
      //获取全局配置
      this.getWholesaleConfig();
      if (!this.data.isBack && this.data.isLogin) {
        //根据权限加载菜单
        this.getAuthorityConfig();
        //获取购物车数量
        cart.get_cart_count();
        //是否有新消息
        this.hasNewMessage();
        //是否开启签到功能
        this.getIntegralRule();
        this.getCheckInInfo();
        this.getVersion();
      }
      this.data.isBack = false;
      this.isShowLink();   //获取是否显示企业微信相关配置
      if(this.data.isLogin){
        this.showSalesman();
        //获取头像
        this.getFace();
      }
    })
  },
  isShowLink:function(){
    let that = this;
    qywx.showlink('customercenter',function(res){
      that.setData({
        showlink:res=='true'
      })
    })
  },
  toLogin:function(){
    profile.loginOut();
    authorize.redirect("store");
    return;
  },
  isCanVisit(callback){
    let that = this;
    this.clearVisitTimer();
    this.data.visitTimer = setTimeout(()=>{
      if(api.isLoginVisit!=undefined){
        that.data.loopCount = 0;
        if ((app.dns.fkFlag != app.dns.proprietor && app.dns.fkId > 0 && app.dns.proprietorId == 0 && !authorize.isLogin('store')) || (api.isLoginVisit&&!authorize.isLogin('store'))) {
          authorize.redirect('store');
        }else{
          callback();
        }
      }else if (that.data.loopCount < 60) {
        that.data.loopCount++;
        that.isCanVisit(callback);
      }
    }, 100)
  },
  clearVisitTimer(){
    if (this.data.visitTimer!=null) {
      clearTimeout(this.data.visitTimer);
      this.data.visitTimer = null;
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    if (this.data.detail_show == 'open') {
      this.setData({
        detail_show: ''
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    this.data.loopCount = 0;
    this.clearVisitTimer();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
    this.data.isBack = false;
    this.onShow();
    this.onLoad();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 获取数量
   *  */
  getIndexCount: function() {
    var that = this;
    let {orderlist}=this.data;
    profile.getIndexCount(function(res) {
      let content = res.Content;
      orderlist.map((item)=>{
        switch (item.key)
        {
          case "dfk":
            item.dot = content.NotPayCount1
          break;
          case "dfh":
            item.dot = content.SendCount
            break;
          case "dsh":
            item.dot = content.ReceiptCount
            break;
          case "dpj":
            item.dot = content.WaitCommentCount
            break;
          case "ywc":
            item.dot = content.EndCount
            break;
        }
      });
      that.setData({
        orderlist:orderlist
      });
    });
    profile.getRetreatCount(function (res) {
      let content = res.Content;
      orderlist.map((item) => {
        switch (item.key) {
          case "thh":
            item.dot = content.RetreatWholesaleCount
            break;
        }
      });
      that.setData({
        orderlist: orderlist
      });
    });   
  },
  /**
   * 获取数量
   *  */
  getIntegralRule: function() {
    var that = this;
    config.getIntegralRule(app.dns.proprietorId,app.dns.fkWay, function(res) {
      var checkinIntegralEnable = false;
      if (res.Success) {
        var checkinIntegralRule = res.Content.CheckinIntegral;
        checkinIntegralEnable = checkinIntegralRule != undefined && checkinIntegralRule.length > 0;
      }
      that.setData({
        checkinIntegralEnable: checkinIntegralEnable
      });
    }, true)
  },
  showDetail: function() {
    router.navigate({
      path: 'userSetting'
    })
  },
  /**
   * 退出登录
   */
  logout: function() {
    //退出登录
    profile.logOut();
    profile.loginOut();
    if (app.dns.proprietor != app.dns.fkFlag){
      app.dns.proprietorId=0;
    }
    app.globalData.index.isReload = true;
    //跳转到登录页面
    authorize.redirect('store');
  },
  /**是否有新消息 */
  hasNewMessage() {
    var that = this;
    info.hasNewMessage(function(res) {
      var hasNew = false;
      if (parseInt(res) > 0) {
        hasNew = true;
      }
      that.setData({
        hasNew: hasNew
      });
    });
  },
  checkHasMenu(key, list){
    for(let t in list){
        if (t == key) {
          return false;
        }
    }
    return true;
  },
  getAuthorityConfig(){
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    var entity = authorize.getEntity() || authorize.getDefault();
    let { menulist, servicelist } = this.data;
    config.getAuthorityConfig(
      fkflag,
      fkid,
      entity.manager.Token,
      function(res){
        if(res.Success){
          let data = res.Content;
          let isDistribution = data.Distribution || 0;
          for (let i = 0; i < menulist.length; i++) {
            if (menulist[i].key == 'shortage') {
              menulist[i].show = data.IsScanty == 1;
            }else if (menulist[i].key == 'comment') {
              menulist[i].show = data.Comment == 1;
            }else if (menulist[i].key == 'credit') {
              menulist[i].show = data.ContactsCredit == 1;
            }else if (menulist[i].key == 'presale') {
              menulist[i].show = data.PreSell == 1;
            }else if (menulist[i].key == 'group') {
              menulist[i].show = data.GroupSell == 1;
            }else if (menulist[i].key == 'distribution') {
              menulist[i].show = isDistribution > 0;
              menulist[i].link = isDistribution > 0 ? (isDistribution == 1 ? ("/" + pagesInfo.distributionMain.url) : ("/" + pagesInfo.distributionApply.url)) : "";
            }else if (menulist[i].key == 'dealing') {
              menulist[i].show = data.TravellingBill == 1;
            }
          }
          for (let i = 0; i < servicelist.length; i++) {
            if (servicelist[i].key == 'market_presale') {
              servicelist[i].show = data.PreSell == 1;
            }else if (servicelist[i].key == 'market_group') {
              servicelist[i].show = data.GroupSell == 1;
            }else if (servicelist[i].key == 'market_sale') {
              servicelist[i].show = data.Special == 1;
            }
          }
          that.setData({
            ProprietorVersion: data.ProprietorVersion,
            EnableSubaccount: data.EnableSubaccount,
            menulist: menulist,
            servicelist: servicelist
          });
        }
      },
      true
    )
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    let { orderlist }=this.data;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Wholesale",
      function(model) {
        that.setData({
          BGColorForMobile: model.BGColorForMobile
        })
        if (!that.data.isBack && that.data.isLogin) {
          for (let i = 0; i < orderlist.length; i++) {
            if (orderlist[i].key == 'dpj') {
              orderlist[i].show = model.OpenComment != false;
            }else if (orderlist[i].key == 'ywc') {
              orderlist[i].show = model.OpenComment == false;
            }
          }
          that.setData({
            orderlist: orderlist,
            IsStoreManagerAccount:model.IsStoreManagerAccount,
            AllowModifyHeadIcon: model.AllowModifyHeadIcon
          }, () => {
            //获取数量
            that.getIndexCount();
          });
          wholesaleSettings.setConfig(model);
        }
      });
  },
  // 上传头像
  bindUploadImg(){
    let AllowModifyHeadIcon = this.data.AllowModifyHeadIcon
    if (!AllowModifyHeadIcon) {
      alert('当前不允许修改头像')
      return
    }
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success (res) {
        const src = res.tempFilePaths[0]
        wx.navigateTo({
          url: `../upload/upload?src=${src}`
        })
      }
    })
  },
  getFace(){
    var that = this;
    var data = {
      proprietor: app.dns.proprietor,
      proprietorId: app.dns.proprietorId,
    }
    config.getAvatar(data,function(res){
      // if(that.data.userFace == res.Content.Face || that.data.userFace == res.Content.Logo)return;
      if(res.Success){
        that.setData({
          userFace:res.Content.Face || res.Content.Logo
        })
      }else{
        util.tips(res.Message)
      }
    })
  },
  //业务员显示
  showSalesman(){
    var that = this;
    profile.salesman(function(res) {
      if(res.Success){
        that.setData({
          salesman:res.Content == 'true'
        })
        console.log(res.Content,that.data.isLogin);
      }
    });
  },
  getVersion(){
    var that = this;
    domain.getDomain((res)=> {
      if (res && res.Success) {
        let item = res.Content;
        if (item) {
          storage.put("version", Number(item.SoftwareVersion) || 1);
          that.setData({
            version:Number(item.SoftwareVersion) || 1
          })
        }
      }
    });
  },
  onClickItem(e){
    if (this.data.isLogin) {
      let url = e.detail || ''
      if (url.includes('dealing/dealing')) {
        let page_dealing_type = storage.get('page_dealing_type', 'online')
        if (page_dealing_type == 'offline' || !page_dealing_type) {
          url = '/packageStore/pages/purchase/dealing_offline/dealing_offline'
        }
      }
      wx.navigateTo({
        url
      })
    }else{
      this.toLogin();
    }
  },
  /**
   * 点击名称
   * 
   * 连续点击5次，将用户信息复制到剪贴板上
   */
  tapName() {
    let tapNamehandle = this.data.tapNamehandle || {}
    let now = new Date()
    let time = now.getTime()
    if (!tapNamehandle.time) {
      tapNamehandle.time = time
      tapNamehandle.count = 1
    } else {
      if ((time - tapNamehandle.time) < 2000) {
        tapNamehandle.time = time
        tapNamehandle.count += 1
      } else {
        tapNamehandle.time = 0
        tapNamehandle.count = 0
      }
    }
    // 连续点击超过5次，复制用户和设备信息至剪贴板
    if (tapNamehandle.count >= 5) {
      tapNamehandle.time = 0
      tapNamehandle.count = 0
      let storeInfo = this.data.storeInfo || {}
      let openid = getStorageSync('openid')
      let systemInfo = wx.getSystemInfoSync()
      let data = {
        storeInfo,
        openid: openid || '',
        time: time,
        systemInfo: systemInfo
      }
      data = JSON.stringify(data)
      wx.setClipboardData({
        data: data,
      })
    }
    this.setData({
      tapNamehandle
    })
  },
})